import axios from "axios";
import { ElLoading } from "element-plus";
import message from "@/utils/Message";
import router from "@/router";

const contentTypeForm = "application/x-www-form-urlencoded;charset=UTF-8";
const contentTypeJson = "application/json";
const contentTypeFile = "multipart/form-data";

const request = (config) => {
    // 似乎是读入数据的部分
    let { url, params, dataType = 'form', showLoading = 'true' } = config;
    let contentType = contentTypeForm;
    switch (dataType) {
        case "json": {
            contentType = contentTypeJson;
            break;
        }
        case "file": {
            contentType = contentTypeFile;
            let param = new FormData();
            for (let key in params) {
                param.append(key, params[key]);
            }
            params = param;
            break;
        }
    };
    // 处理axios相关的部分
    const instantce = axios.create({
        baseURL: '/api',
        timeout: 10 * 1000,
        headers: {
            'Content-Type': contentType,
            'X-Requested-With': 'XMLHttpRequest',
        }
    });

    
    // 请求前拦截
    let loading = null;
    instantce.interceptors.request.use(
        (config) => {
            if (showLoading) {
                loading = ElLoading.service({
                    lock: true,
                    text: '服务器祈祷(折寿)中。。。',
                    background: 'rgba(0,0,0,0.7)',
                })
            }
            return config;
        },
        (error) => {
            if (showLoading && loading) {
                loading.close();
            };
            message.error("发送请求失败");
            return Promise.reject("发送请求失败");
        }
    );
    // 请求后拦截
    instantce.interceptors.response.use(
        (response) => {
            if (showLoading && loading) {
                loading.close();
            }
            const responseData = response.data;
            if (responseData.status == 'error') {

                if (config.errorCallback) {
                    config.errorCallback();
                }

                return Promise.reject(responseData.info);
            } else {
                if (responseData.code == 200) {
                    return responseData;
                } else if (responseData.code == 901) {
                    setTimeout(()=>{
                        router.push("/");
                    },2000);
                    return Promise.reject("登录超时");
                }


                return responseData;
            }
        },
        (error) => {
            console.log(error);
            if (showLoading && loading) {
                loading.close();
            }
            return Promise.reject("网络异常")
        }
    );

    return instantce.post(url, params).catch(error => {
        message.error(error);
        return null;
    });
    // promise 为异步非阻塞类
    // 关于promise then()为成功后执行[或用于获取结果],catch为失败后执行[获取错误]
    // resolve为成功后执行,rejects为失败后执行
    // let result = new Promise((resolve, rejects) => {
    //     instantce.post(url, params).then(res => {
    //         resolve(res);
    //     }).catch(error => {
    //         message.error(error);
    //         rejects(error);
    //     })
    // })
    // return result;

}

export default request;